package com.minarto.display {
	import scaleform.clik.core.UIComponent;
	import de.polygonal.core.ObjectPool;
	import com.minarto.utils.GPool;
	import com.minarto.events.CustomEvent;
	import com.minarto.display.loader.ChainLoader;
	import flash.display.*;
	import flash.events.*;

	
	/**
	 * @author KIMMINHWAN
	 */
	public class MainUIContainer extends UIComponent {
		protected var	idField:String = "id",
						srcField:String = "src",
						xField:String = "x",
						yField:String = "y",
						visibleField:String = "visible";
		
		
		protected var _datas:Array;
		public function getDatas():Array {
			return	_datas;
		}
		
		
		public function MainUIContainer() {
			super();
			documentInit(this);
		}
		
		override protected function configUI():void{
			mouseEnabled = false;
		}
		
		
		public function clear():void{
			var i:uint = _datas ? _datas.length : 0;
			while(i--){
				removeChild(getChildByName(_datas[i][idField]));
			}
			
			_datas = null;
		}
		
		
		public function loadUI(...$data):void {
			var i:uint, c:uint, f:Function, loader:ChainLoader, p:ObjectPool;
			
			_datas = $data;
			c = _datas.length;
			if (c) {
				f = loader.addSrc;
				
				for (i = 0; i < c; i++) {
					f(_datas[i][srcField]);
				}
				
				p = GPool.getPool(ChainLoader);
				loader = p.object;
				loader.addEventListener(CustomEvent.LAST_COMPLETE, function($e:Event):void {
					var contents:Vector.<DisplayObject>, d:DisplayObject, u:*, v:Boolean;
					
					v = visible;
					visible = false;
					
					loader.removeEventListener(CustomEvent.LAST_COMPLETE, arguments.callee);
					
					contents = loader.getContents();
					f = addChild;
					
					for (i = 0; i < c; i++) {
						u = _datas[i];
						d = contents[i];
						if(d){
							d.x = u[xField];
							d.y = u[yField];
							d.name = u[idField];
							d.visible = u[visibleField];
							u.content = d;
							f(d);
						}
					}
					
					p.object = loader;
					
					visible = v;
				}, false, 0, true);
				
				loader.load();
			}
		}
		
		protected function getEvtTargetUI($e:MouseEvent):DisplayObject{
			var u:DisplayObject = $e.target as DisplayObject;
			
			while(u.parent != this){
				u = u.parent;
			}
			
			return	u;
		}
	}
}
